import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Checkbox, 
  Typography, 
  message,
  Alert,
  Modal,
  Space
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
  EyeOutlined, 
  EyeInvisibleOutlined,
  ArrowRightOutlined,
  ProjectOutlined,
  GithubOutlined,
  GoogleOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';

const { Title, Text, Link } = Typography;

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { login, isAuthenticated } = useAuth();

  // 检查是否已登录
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/dashboard');
    }
  }, [isAuthenticated, navigate]);

  const handleSubmit = async (values) => {
    if (!values.username || !values.password) {
      setError('请输入用户名和密码');
      return;
    }

    setLoading(true);
    setError('');
    
    try {
      console.log('开始登录，用户名:', values.username);
      
      // 使用AuthContext统一的登录方法
      const result = await login(values.username, values.password);
      
      console.log('登录结果:', result);
      
      // 记住我功能
      if (values.remember) {
        localStorage.setItem('rememberMe', 'true');
        localStorage.setItem('rememberedUsername', values.username);
      } else {
        localStorage.removeItem('rememberMe');
        localStorage.removeItem('rememberedUsername');
      }
      
      if (result.success) {
        // 登录成功，显示成功弹窗
        Modal.success({
          title: '登录成功',
          content: result.message || '欢迎回来，正在进入系统...',
          centered: true,
          okText: '确定',
          onOk: () => {
            navigate('/dashboard');
          }
        });
      } else {
        // 登录失败，显示错误弹窗
        Modal.error({
          title: '登录失败',
          content: result.error || '用户名或密码错误，请重试',
          centered: true,
          okText: '确定'
        });
      }
    } catch (error) {
      console.error('登录异常:', error);
      setError(error.message || '登录失败，请检查网络连接或稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 初始化记住的用户名
  useEffect(() => {
    const rememberMe = localStorage.getItem('rememberMe');
    const rememberedUsername = localStorage.getItem('rememberedUsername');
    
    if (rememberMe === 'true' && rememberedUsername) {
      form.setFieldsValue({
        username: rememberedUsername,
        remember: true
      });
    }
  }, [form]);

  const handleForgotPassword = () => {
    message.info('密码重置功能开发中，请联系管理员');
  };

  const handleSocialLogin = (provider) => {
    message.info(`${provider} 登录功能开发中...`);
  };

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      width: '100vw',
      height: '100vh',
      background: 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      overflow: 'hidden',
      margin: 0,
      padding: '40px'
    }}>
      {/* 知识图谱背景装饰 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        opacity: 1,
        pointerEvents: 'none',
        zIndex: 1
      }}>
        {/* 网络节点 */}
        <div style={{
          position: 'absolute',
          top: '10%',
          left: '15%',
          width: '12px',
          height: '12px',
          borderRadius: '50%',
          background: '#165DFF',
          boxShadow: '0 0 30px rgba(22, 93, 255, 0.6)',
          animation: 'pulse 3s ease-in-out infinite'
        }} />
        <div style={{
          position: 'absolute',
          top: '25%',
          left: '8%',
          width: '10px',
          height: '10px',
          borderRadius: '50%',
          background: '#52c41a',
          boxShadow: '0 0 25px rgba(82, 196, 26, 0.6)',
          animation: 'pulse 4s ease-in-out infinite',
          animationDelay: '1s'
        }} />
        <div style={{
          position: 'absolute',
          top: '40%',
          left: '5%',
          width: '14px',
          height: '14px',
          borderRadius: '50%',
          background: '#faad14',
          boxShadow: '0 0 35px rgba(250, 173, 20, 0.6)',
          animation: 'pulse 3.5s ease-in-out infinite',
          animationDelay: '0.5s'
        }} />
        <div style={{
          position: 'absolute',
          top: '60%',
          left: '12%',
          width: '11px',
          height: '11px',
          borderRadius: '50%',
          background: '#722ed1',
          boxShadow: '0 0 28px rgba(114, 46, 209, 0.6)',
          animation: 'pulse 4.5s ease-in-out infinite',
          animationDelay: '2s'
        }} />
        <div style={{
          position: 'absolute',
          top: '80%',
          left: '20%',
          width: '13px',
          height: '13px',
          borderRadius: '50%',
          background: '#f5222d',
          boxShadow: '0 0 32px rgba(245, 34, 45, 0.6)',
          animation: 'pulse 3.8s ease-in-out infinite',
          animationDelay: '1.5s'
        }} />
        
        {/* 右侧节点 */}
        <div style={{
          position: 'absolute',
          top: '15%',
          right: '10%',
          width: '11px',
          height: '11px',
          borderRadius: '50%',
          background: '#13c2c2',
          boxShadow: '0 0 28px rgba(19, 194, 194, 0.6)',
          animation: 'pulse 4.2s ease-in-out infinite',
          animationDelay: '0.8s'
        }} />
        <div style={{
          position: 'absolute',
          top: '35%',
          right: '18%',
          width: '12px',
          height: '12px',
          borderRadius: '50%',
          background: '#eb2f96',
          boxShadow: '0 0 30px rgba(235, 47, 150, 0.6)',
          animation: 'pulse 3.3s ease-in-out infinite',
          animationDelay: '2.2s'
        }} />
        <div style={{
          position: 'absolute',
          top: '55%',
          right: '8%',
          width: '10px',
          height: '10px',
          borderRadius: '50%',
          background: '#fa8c16',
          boxShadow: '0 0 25px rgba(250, 140, 22, 0.6)',
          animation: 'pulse 4.8s ease-in-out infinite',
          animationDelay: '1.2s'
        }} />
        <div style={{
          position: 'absolute',
          top: '75%',
          right: '15%',
          width: '13px',
          height: '13px',
          borderRadius: '50%',
          background: '#1890ff',
          boxShadow: '0 0 32px rgba(24, 144, 255, 0.6)',
          animation: 'pulse 3.6s ease-in-out infinite',
          animationDelay: '0.3s'
        }} />
        
        {/* 连接线 */}
        <svg style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none'
        }}>
          <defs>
            <linearGradient id="lineGradient1" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#165DFF" stopOpacity="0.4" />
              <stop offset="100%" stopColor="#52c41a" stopOpacity="0.4" />
            </linearGradient>
            <linearGradient id="lineGradient2" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#faad14" stopOpacity="0.4" />
              <stop offset="100%" stopColor="#722ed1" stopOpacity="0.4" />
            </linearGradient>
            <linearGradient id="lineGradient3" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#f5222d" stopOpacity="0.4" />
              <stop offset="100%" stopColor="#13c2c2" stopOpacity="0.4" />
            </linearGradient>
          </defs>
          
          {/* 连接线路径 */}
          <path
            d="M 15% 10% Q 30% 5% 90% 15%"
            stroke="url(#lineGradient1)"
            strokeWidth="2"
            fill="none"
            strokeDasharray="5,5"
          />
          <path
            d="M 8% 25% Q 25% 30% 82% 35%"
            stroke="url(#lineGradient2)"
            strokeWidth="2"
            fill="none"
            strokeDasharray="3,7"
          />
          <path
            d="M 5% 40% Q 40% 45% 92% 55%"
            stroke="url(#lineGradient3)"
            strokeWidth="2"
            fill="none"
            strokeDasharray="8,4"
          />
          <path
            d="M 12% 60% Q 50% 65% 85% 75%"
            stroke="url(#lineGradient1)"
            strokeWidth="2"
            fill="none"
            strokeDasharray="6,6"
          />
          <path
            d="M 20% 80% Q 60% 70% 85% 55%"
            stroke="url(#lineGradient2)"
            strokeWidth="2"
            fill="none"
            strokeDasharray="4,8"
          />
          
          {/* 垂直连接线 */}
          <path
            d="M 15% 10% L 8% 25%"
            stroke="rgba(22, 93, 255, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          <path
            d="M 8% 25% L 5% 40%"
            stroke="rgba(82, 196, 26, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          <path
            d="M 5% 40% L 12% 60%"
            stroke="rgba(250, 173, 20, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          <path
            d="M 12% 60% L 20% 80%"
            stroke="rgba(114, 46, 209, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          
          {/* 右侧连接线 */}
          <path
            d="M 90% 15% L 82% 35%"
            stroke="rgba(19, 194, 194, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          <path
            d="M 82% 35% L 92% 55%"
            stroke="rgba(235, 47, 150, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
          <path
            d="M 92% 55% L 85% 75%"
            stroke="rgba(250, 140, 22, 0.2)"
            strokeWidth="1.5"
            fill="none"
          />
        </svg>
        
        {/* 浮动粒子效果 */}
        <div style={{
          position: 'absolute',
          top: '20%',
          left: '30%',
          width: '4px',
          height: '4px',
          borderRadius: '50%',
          background: '#165DFF',
          animation: 'float 6s ease-in-out infinite',
          animationDelay: '0s'
        }} />
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '70%',
          width: '5px',
          height: '5px',
          borderRadius: '50%',
          background: '#52c41a',
          animation: 'float 8s ease-in-out infinite',
          animationDelay: '2s'
        }} />
        <div style={{
          position: 'absolute',
          top: '70%',
          left: '40%',
          width: '3px',
          height: '3px',
          borderRadius: '50%',
          background: '#faad14',
          animation: 'float 7s ease-in-out infinite',
          animationDelay: '4s'
        }} />
      </div>
      
      {/* CSS动画定义 */}
      <style>
        {`
          @keyframes float {
            0%, 100% { transform: translateY(0px) translateX(0px); opacity: 0.4; }
            25% { transform: translateY(-15px) translateX(8px); opacity: 0.8; }
            50% { transform: translateY(-8px) translateX(-12px); opacity: 1; }
            75% { transform: translateY(-20px) translateX(5px); opacity: 0.6; }
          }
          
          @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.8; }
            50% { transform: scale(1.2); opacity: 1; }
          }
        `}
      </style>
      
      {/* 主容器 */}
      <div style={{
        width: '100%',
        maxWidth: '1200px',
        height: '100%',
        maxHeight: '700px',
        background: '#ffffff',
        borderRadius: '24px',
        boxShadow: '0 20px 60px rgba(0, 0, 0, 0.1)',
        display: 'flex',
        overflow: 'hidden',
        position: 'relative',
        zIndex: 2
      }}>
        {/* 左侧蓝色区域 */}
        <div style={{
          width: '50%',
          height: '100%',
          background: 'linear-gradient(135deg, #165DFF 0%, #0F4CD4 100%)',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          position: 'relative',
          overflow: 'hidden',
          padding: '60px 40px'
        }}>
          {/* 装饰元素 */}
          <div style={{
            position: 'absolute',
            top: '-100px',
            right: '-100px',
            width: '300px',
            height: '300px',
            background: 'rgba(255, 255, 255, 0.08)',
            borderRadius: '50%',
            filter: 'blur(60px)'
          }} />
          <div style={{
            position: 'absolute',
            bottom: '-150px',
            left: '-150px',
            width: '400px',
            height: '400px',
            background: 'rgba(255, 255, 255, 0.05)',
            borderRadius: '50%',
            filter: 'blur(80px)'
          }} />
          
          {/* Logo区域 */}
          <div style={{ 
            position: 'absolute',
            top: '40px',
            left: '40px',
            display: 'flex', 
            alignItems: 'center', 
            zIndex: 10 
          }}>
            <div style={{
              width: '48px',
              height: '48px',
              borderRadius: '12px',
              background: 'rgba(255, 255, 255, 0.2)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#fff',
              backdropFilter: 'blur(20px)',
              border: '1px solid rgba(255, 255, 255, 0.1)'
            }}>
              <ProjectOutlined style={{ fontSize: '24px' }} />
            </div>
            <Title level={4} style={{ 
              color: '#fff', 
              margin: '0 0 0 12px',
              textShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
              fontSize: '18px',
              fontWeight: 600
            }}>
              知识图谱管理系统
            </Title>
          </div>

          {/* 中心内容 */}
          <div style={{ 
            textAlign: 'center',
            zIndex: 10,
            maxWidth: '400px'
          }}>
            <img
              src="https://design.gemcoder.com/staticResource/echoAiSystemImages/00f913136e426eff1d4c34d3c12ee288.png"
              alt="知识图谱可视化"
              style={{
                width: '100%',
                maxWidth: '320px',
                borderRadius: '16px',
                boxShadow: '0 20px 40px rgba(0, 0, 0, 0.2)',
                transform: 'rotate(1deg)',
                transition: 'all 0.4s ease',
                border: '2px solid rgba(255, 255, 255, 0.1)',
                marginBottom: '32px'
              }}
              onMouseEnter={(e) => {
                e.target.style.transform = 'rotate(0deg) scale(1.02)';
                e.target.style.boxShadow = '0 25px 50px rgba(0, 0, 0, 0.3)';
              }}
              onMouseLeave={(e) => {
                e.target.style.transform = 'rotate(1deg) scale(1)';
                e.target.style.boxShadow = '0 20px 40px rgba(0, 0, 0, 0.2)';
              }}
            />
            
            <Title level={3} style={{ 
              color: '#fff', 
              marginBottom: '16px',
              fontSize: '24px',
              fontWeight: 600,
              textShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
            }}>
              智能知识管理平台
            </Title>
            <Text style={{ 
              color: 'rgba(255, 255, 255, 0.85)', 
              fontSize: '14px',
              lineHeight: '1.6',
              display: 'block'
            }}>
              构建、管理和可视化复杂知识网络，助力团队协作与决策，释放知识价值
            </Text>
          </div>
        </div>

        {/* 右侧登录表单区域 */}
        <div style={{
          width: '50%',
          height: '100%',
          background: '#ffffff',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          padding: '60px 50px',
          position: 'relative'
        }}>
          {/* 登录容器 */}
          <div style={{
            width: '100%',
            maxWidth: '360px'
          }}>
            {/* 登录标题 */}
            <div style={{ 
              textAlign: 'center',
              marginBottom: '40px' 
            }}>
              <Title level={2} style={{ 
                marginBottom: '8px',
                fontSize: '28px',
                fontWeight: 600,
                color: '#1D2129'
              }}>
                欢迎登录
              </Title>
              <Text style={{ 
                color: '#4E5969', 
                fontSize: '14px'
              }}>
                请输入您的账号信息登录系统
              </Text>
            </div>

            {/* 登录表单 */}
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              size="large"
            >
              {/* 用户名/邮箱 */}
              <Form.Item
                name="username"
                label={<span style={{ fontSize: '14px', fontWeight: 500, color: '#1D2129' }}>用户名/邮箱</span>}
                rules={[{ required: true, message: '请输入用户名或邮箱' }]}
                style={{ marginBottom: '20px' }}
              >
                <Input
                  prefix={<UserOutlined style={{ color: '#C9CDD4', fontSize: '16px' }} />}
                  placeholder="请输入用户名或邮箱"
                  style={{
                    height: '44px',
                    borderRadius: '8px',
                    fontSize: '14px',
                    border: '1px solid #E5E6EB',
                    backgroundColor: '#FAFBFC'
                  }}
                />
              </Form.Item>

              {/* 密码 */}
              <Form.Item
                name="password"
                label={<span style={{ fontSize: '14px', fontWeight: 500, color: '#1D2129' }}>密码</span>}
                rules={[{ required: true, message: '请输入密码' }]}
                style={{ marginBottom: '16px' }}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: '#C9CDD4', fontSize: '16px' }} />}
                  placeholder="请输入密码"
                  iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                  style={{
                    height: '44px',
                    borderRadius: '8px',
                    fontSize: '14px',
                    border: '1px solid #E5E6EB',
                    backgroundColor: '#FAFBFC'
                  }}
                />
              </Form.Item>

              {/* 错误提示 */}
              {error && (
                <Alert
                  message={error}
                  type="error"
                  showIcon
                  style={{ marginBottom: '16px' }}
                  closable
                  onClose={() => setError('')}
                />
              )}

              {/* 记住我和忘记密码 */}
              <Form.Item style={{ marginBottom: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox style={{ fontSize: '14px', color: '#4E5969' }}>记住我</Checkbox>
                  </Form.Item>
                  <Link 
                    onClick={handleForgotPassword}
                    style={{ 
                      color: '#165DFF',
                      fontSize: '14px'
                    }}
                  >
                    忘记密码?
                  </Link>
                </div>
              </Form.Item>

              {/* 登录按钮 */}
              <Form.Item style={{ marginBottom: '24px' }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  style={{
                    width: '100%',
                    height: '44px',
                    fontSize: '16px',
                    background: 'linear-gradient(135deg, #165DFF 0%, #0F4CD4 100%)',
                    border: 'none',
                    borderRadius: '8px',
                    fontWeight: 500,
                    boxShadow: '0 4px 12px rgba(22, 93, 255, 0.3)'
                  }}
                  icon={!loading && <ArrowRightOutlined />}
                >
                  {loading ? '登录中...' : '登录'}
                </Button>
              </Form.Item>

              {/* 其他登录方式 */}
              <div style={{ textAlign: 'center', marginBottom: '24px' }}>
                <Text style={{ color: '#86909C', fontSize: '14px', marginBottom: '16px', display: 'block' }}>
                  其他登录方式
                </Text>
                <Space size={16}>
                  <Button
                    shape="circle"
                    size="large"
                    style={{
                      width: '44px',
                      height: '44px',
                      border: '1px solid #E5E6EB',
                      backgroundColor: '#FAFBFC'
                    }}
                    icon={<GithubOutlined style={{ fontSize: '18px', color: '#1D2129' }} />}
                    onClick={() => handleSocialLogin('GitHub')}
                  />
                  <Button
                    shape="circle"
                    size="large"
                    style={{
                      width: '44px',
                      height: '44px',
                      border: '1px solid #E5E6EB',
                      backgroundColor: '#FAFBFC'
                    }}
                    icon={<GoogleOutlined style={{ fontSize: '18px', color: '#1D2129' }} />}
                    onClick={() => handleSocialLogin('Google')}
                  />
                  <Button
                    shape="circle"
                    size="large"
                    style={{
                      width: '44px',
                      height: '44px',
                      border: '1px solid #E5E6EB',
                      backgroundColor: '#FAFBFC',
                      fontSize: '14px',
                      fontWeight: 600,
                      color: '#1D2129'
                    }}
                    onClick={() => handleSocialLogin('Azure')}
                  >
                    Az
                  </Button>
                </Space>
              </div>

              {/* 注册链接 */}
              <div style={{
                textAlign: 'center',
                color: '#86909C',
                fontSize: '14px'
              }}>
                <Text style={{ color: '#86909C' }}>
                  还没有账号？
                </Text>
                <Link 
                  style={{ 
                    color: '#165DFF',
                    marginLeft: '4px'
                  }}
                  onClick={() => message.info('注册功能开发中...')}
                >
                  立即注册
                </Link>
              </div>

            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;